#include "testCo.h"

TestCo::TestCo()
{

}

void TestCo::test()
{
	jzco_spawn([]{
		QTcpServer server;
		auto task1 = jzco_spawn([&server] {
			JZCoTcpServer co_server(&server);
			server.listen(QHostAddress("127.0.0.1"), 19888);

			while (true)
			{
				JZCoTcpSocket s = co_server.accept().await();
				if (s.isNull())
				{
					qDebug() << "server exit.";
					return;
				}

				jzco_spawn([s] {
					JZCoTcpSocket socket = s;
					while (true)
					{
						QByteArray buffer = socket.readAll().await();
						if (buffer.isEmpty())
							break;

						qDebug() << "server recv:" << buffer;
						socket.write(buffer).await();
					}
					});
			}
			});

		auto task2 = jzco_spawn([&server] {
			QElapsedTimer t;
			t.start();
			jzco_sleep(10 * 1000);
			server.close();
			qDebug() << "close server: " << t.elapsed();
			});

		jzco_waitCoroutine({ task1 ,task2 });
	});

	for (int i = 0; i < 100; i++)
	{
		jzco_spawn([i] {
			jzco_sleep(1000);

			QTcpSocket *socket = new QTcpSocket();
			JZCoTcpSocket client(socket);
			bool ret = client.connectToHost("127.0.0.1", 19888).await();
			Q_ASSERT(ret);

			QByteArray buffer = ("hello world, " + QString::number(i)).toUtf8();
			client.write(buffer).await();

			buffer = client.readAll().await();
			qDebug() << "client recv." << buffer;

			socket->deleteLater();
		});
	}
}